import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import router from '@/router'

// 基地址
const service = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000
})

// // 导出一个新axios实例调用接口函数， 返回值promise
// export default ({ url, method = 'get', params, data, headers }) => {
//   const promise = service({ url, method, params, data, headers })
//   return promise
// }

// 请求拦截器

service.interceptors.request.use((config) => {
  if (store.state.user.token) {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
  if (response.status === 401) {
    Toast('登录失败')
    router.push('/login')
    store.commit('user/removeToken')
  } else {
    return response
  }
}, (error) => {
  return Promise.reject(error)
})

export default service
